<template>
  <div class="app-container">
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input style="width: 200px;" v-model="pageParam.superSearchKeyWord" placeholder="关键字查询..." class="filter-item"
                @keyup.enter.native="handleFilter" @input="handleFilter" />

      <el-option v-for="item in newsCategoryList" :key="item.id" :label="item.categoryName" :value="item.id" />

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" @sort-change="sortChange" fit highlight-current-row style="width: 100%;">

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">



            <el-form-item label="姓名">
              <span>{{ row.realName}}</span>
            </el-form-item>

            <el-form-item label="年龄">
              <span>{{ row.age }}</span>
            </el-form-item>


            <!-- <el-form-item label="新闻内容">
              <span>{{ row.newsContent }}</span>
            </el-form-item> -->


            <el-form-item label="性别">
              <span>{{ row.gender }}</span>
            </el-form-item>

            <el-form-item label="电话">
              <span>{{ row.telephone }}</span>
            </el-form-item>

            <el-form-item label="科室">
              <span>{{ row.name }}</span>
            </el-form-item>

            <el-form-item label="职位">
              <span>{{ row.roleName }}</span>
            </el-form-item>

<!--            <el-form-item label="状态">-->
<!--              <span>（0为正常，1为下架）</span>-->
<!--              <span>{{ row.status }}</span>-->
<!--            </el-form-item>-->

          </el-form>
        </template>
      </el-table-column>

      <!-- 表格字段 -->
      <el-table-column prop="realName" label="姓名">
      </el-table-column>

      <el-table-column prop="age" label="年龄">
      </el-table-column>

      <el-table-column prop="gender" label="性别">
      </el-table-column>

      <el-table-column prop="telephone" label="电话">
      </el-table-column>
      <el-table-column prop="name" label="科室">
      </el-table-column>
      <el-table-column prop="roleName" label="职位">
      </el-table-column>


      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-if="roles[0] == 'news_admin' && row.checkStatus == 0" size="small" type="success" @click="confirmCheck(row)">确认审核</el-button>
          <el-button v-if="roles[0] == 'news_admin' && row.checkStatus != 0" size="small" type="info" @click="confirmCheck(row)">撤回审核</el-button>
          <el-button v-if="(row.checkStatus == 1) &&(roles[0] == 'news_admin'||roles[0] == 'news_editor')" size="small" type="success" @click="updateCheckStatus(row)">发布</el-button>
          <el-button v-if="(roles[0] == 'news_admin'||roles[0] == 'news_editor')&&(row.checkStatus == 2)" size="small" type="warning" @click="updateCheckStatus(row)">撤销</el-button>
          <el-button size="small" v-if="roles[0] == 'super_admin'||roles[0] == 'hr'" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="getListByPage" />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">



        <!-- 弹窗 -->

        <el-form-item label="职位">
          <el-select v-model="temp.roleId" placeholder="请选择科室">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item >


        <el-form-item label="科室">
          <el-select v-model="temp.postId" placeholder="请选择科室">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item >



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from 'vuex'
  //图片黏贴插件
  import '../../assets/js/image-paste.min.js'
  //quill富文本编辑器css
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  //quill富文本编辑器 组件倒入
  import {
    quillEditor
  } from 'vue-quill-editor'

  import {
    getToken
  } from '@/utils/auth'

  import {
    searchSomePersonByPage,
    getAllRole,
    deletePersonTrue,
    // addOneDrug,
    // deleteOneDrugTrue,
    updatePerson
  } from '@/api/hr/Hr'

  //导入科室列表api
  import {getAlldepartment} from "@/api/appointment/appointment"


  //倒入文件上传api
  import {
    uploadImage
  } from '@/api/file'

  //导入组件  记得声明组件
  import Pagination from '@/components/Pagination'

  export default {
    components: { //在这里声明组件
      Pagination,
      quillEditor
    },
    computed: {
      ...mapGetters({
        'userName': 'name',
        'roles': 'roles',
        'storeNickName': 'nickName'
      }),
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    },
    data() {
      return {
        editorOption: {
          modules: {

            imagePaste: {
              addImageBlob: function(blob, callback) {
                var formData = new FormData()

                formData.append('image', blob)

                // console.log(blob, callback)

                // your upload function, get the uploaded image url, add then
                uploadImage(formData).then(res => {
                  console.log(res)
                  // let imageUrl =
                  //   'https://wnbucket.oss-cn-shanghai.aliyuncs.com/15930888655881592094766089.jpg'

                  callback(res.content)
                }).catch(err => {
                  console.log(err)
                })


              }
            }

          }
        },

        dialogImageUrl: '',
        dialogVisible: false,
        headerToken: {
          'Authorization': getToken()
        },
        imageUploadAction: process.env.VUE_APP_BASE_API + '/file/uploadImage',
        list: [], //列表数据
        total: 0,
        createTimeOrderOptions: [{
          label: '创建时间 升序',
          key: '+createTime',
          value: 'createTime asc'
        },
          {
            label: '创建时间 降序',
            key: 'createTime',
            value: 'createTime desc'
          }
        ],

        listQuery: { //分页 排序  查询参数
          pageNum: 1,
          pageSize: 5
        },
        fieldQuery: { // 按字段查询
          realName: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        temp: {
          id: '',
          realName: '',
          name: '',
          age: '',
          genter: '',
          roleName:'',
          telephone:'',
          postId:''

          // status: undefined,
          // isDeleted: undefined,
        },
        departmentList:[

        ],
        roleList:[

        ],

        tempImageList: [

        ],
        newsCategoryList: [

        ],
        rules: {},
        pageParam: {
          pageNum: 1,
          pageSize: 5,
          model: {

          },
          orderParams: [
            'createTime desc'
          ],
          superSearchKeyWord: ''
        },
        roleList: []

      }
    },
    created() {
      this.getListByPage()
    },
    methods: {

      getRoleList(){
        getAllRole().then(res=>{
          this.roleList=res.content
        }).catch(err => {
          console.log(err)
        })
      },

      getAllDepartment(){
        getAlldepartment().then(res=>{
          this.departmentList=res.content
        }).catch(err => {
          console.log(err)
        })
      },
      sortChange(val) {
        // console.log("排序参数",val)
        let prop = val.prop
        let order = val.order === 'ascending' ? 'asc' : 'desc'
        let orderParam = prop + ' ' + order
        // console.log(orderParam)
        for (let i = 0; i < this.pageParam.orderParams.length; i++) {
          if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
            this.pageParam.orderParams.splice(i, 1)
          }
        }
        this.pageParam.orderParams.push(orderParam)
        console.log(this.pageParam.orderParams)
        this.getListByPage()
      },
      getNewsCategoryList() {
        let pageNum = 1
        let pageSize = 5
        let orderParams = []
        let model = {
          checkStatus: 1 //只查询 已经审核通过的分类
        }
        let pageParam = {
          pageNum,
          pageSize,
          orderParams,
          model
        }

      },
      getTempImageList() {
        //清空文件列表
        this.tempImageList = []

        let tempPageParam = this.pageParam
        tempPageParam.model = {
          productId: this.temp.id
        }
        tempPageParam.pageSize = 5
        searchSomeProductimageByPage(tempPageParam).then(res => {
          // console.log(res)
          let resList = res.content.list
          let tempImageData = {
            name: '',
            url: '',
            key: ''
          }
          this.$refs.imagesUpload.clearFiles()
          for (let i = 0; i < resList.length; i++) {
            tempImageData.name = resList[i].imageUrl
            tempImageData.url = resList[i].imageUrl
            tempImageData.key = resList[i].imageUrl
            this.tempImageList.push(tempImageData)
          }

        }).catch(err => {
          console.log(err)
        })
      },
      getListByPage() {
        this.pageParam.pageNum = this.listQuery.pageNum
        this.pageParam.pageSize = this.listQuery.pageSize

        console.log(this.pageParam.orderParams)

        searchSomePersonByPage(this.pageParam).then(res => {
          //console.log(res)
          this.list = res.content.list
          this.total = res.content.total
        }).catch(err => {
          console.log(err)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getListByPage()
      },
      handleCreate() {
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        this.getNewsCategoryList()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        console.log('edit:' + row)
        this.temp = Object.assign({}, row) // copy obj
        this.temp.id = row.id
        this.dialogStatus = 'update'
        // this.getTempImageList() // 展示商品图片列表
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row, index) {

        let temp = {
          id: row.id
        }

        deletePersonTrue(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })

      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addOneDrug(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updatePerson(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })




      },
      resetTemp() {
        this.temp = {
          id: '',
          no: '',
          name: '',
          price: '',
          stock: '',
          status: undefined,
          isDeleted: undefined,
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);

        let imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
        // let imageUrl = ''
        let productImageData = {
          imageUrl: imageUrl
        }
        deleteSomeProductimageTrueByCondition(productImageData).then(() => {

        })

      },
      handlePictureCardPreview(file) {
        console.log(file, fileList);
        // this.dialogImageUrl = file.url;
        console.log(file.url)
        this.temp.productImages = file.url
        this.dialogVisible = true;
      },
      handleImageSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        // this.temp.productImages = res.content

        let productImageData = {
          imageUrl: res.content,
          productId: this.temp.id
        }
        addOneProductimage(productImageData).then(() => {

        })
      },
      handleAvatarSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        this.temp.newsImage = res.content
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const fileName = file.name
        const isImage = /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName);
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 gif|jpg|jpeg|png|gif|jpg|png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      },
      onEditorBlur(quill) {
        // console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        // console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        // console.log('editor ready!', quill)
      },
      onEditorChange({
                       quill,
                       html,
                       text
                     }) {
        // console.log('editor change!', quill, html, text)
        this.temp.description = html
      },
      categoryChange(){
        this.getListByPage()
      },
      updateCheckStatus(row){
        // console.log('edit:' + row)
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus==1?2:1
        updateDrug(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus==1?'撤销成功':'发布成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      confirmCheck(row){
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus==0?1:0
        updateDrug(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus==0?'审核成功':'取消审核成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      }
    },
    mounted(){
      this.getNewsCategoryList(),
     this.getAllDepartment(),
       this.getRoleList()
    }




  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
